import axios from 'axios'
import { cloneDeep, isEmpty } from 'lodash'
import pathToRegexp from 'path-to-regexp'
import { message } from 'antd'
import { CANCEL_REQUEST_MESSAGE } from 'utils/constant'
import qs from 'qs'
import store from 'store'
import { router } from 'utils'

const { CancelToken } = axios
window.cancelRequest = new Map()
// let sessionToken = undefined;
export default function request(options) {
  let { data, url, method = 'post' } = options
  const cloneData = cloneDeep(data)

  try {
    let domain = ''
    const urlMatch = url.match(/[a-zA-z]+:\/\/[^/]*/)
    if (urlMatch) {
      ;[domain] = urlMatch
      url = url.slice(domain.length)
    }

    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)

    for (const item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domain + url
  } catch (e) {
    message.error(e.message)
  }

  options.url =
    method.toLocaleLowerCase() === 'get'
      ? `${url}${isEmpty(cloneData) ? '' : '?'}${qs.stringify(cloneData)}`
      : url

  options.cancelToken = new CancelToken(cancel => {
    window.cancelRequest.set(Symbol(Date.now()), {
      pathname: window.location.pathname,
      cancel,
    })
  })
  // console.log(JSON.stringify(options.url))
  let sessionToken
  // if (options.url.indexOf("logout") != -1) {
  //   // sessionToken = undefined;
  //   // sessionToken = sessionStorage.getItem("mr-ly-sessionToken-session");
  // } else
  if (!sessionToken) {
    sessionToken = sessionStorage.getItem('mr-ly-sessionToken-session')
    if (!sessionToken) {
      sessionToken = store.get('mr-ly-sessionToken')
      if (sessionToken) {
        sessionStorage.setItem('mr-ly-sessionToken-session', sessionToken)
      }
    }
  }
  // var sessionToken = store.get('mr-ly-sessionToken')
  // console.log("sessionToken:" + sessionToken);
  options.headers = {
    ...options.headers,
    // 'Access-Control-Allow-Origin': '*',
    'Content-type': 'application/json',
    'X-LC-Id': 'moCEMo7MPHzcVWMi8t9RlIXE-gzGzoHsz',
    'X-LC-Key': 'Jrx998il8cU9zPN3xnhQNhaj',
    // ...(sessionToken ? { 'X-LC-Session': sessionToken } : {}),
  }
  // options.withCredentials = true;
  options.baseURL = 'https://moCEMo7M.engine.lncld.net/1.1/functions' //'https://avoscloud.com/1.1/functions' // // // 'https://moCEMo7M.avoscloud.com/1.1/functions' //.engine.lncld.net   //'http://localhost:3000/1.1/functions'  //'https://moCEMo7M.engine.lncld.net/1.1/functions';moCEMo7M,rohmehlw
  options.data = {
    ...options.data,
    session: sessionToken,
  }
  return axios(options)
    .then(response => {
      const { statusText, status, data } = response

      let result = {}
      if (typeof data === 'object') {
        result = data
        if (Array.isArray(data)) {
          result.list = data
        }
      } else {
        result.data = data
      }

      return Promise.resolve({
        success: true,
        message: statusText,
        statusCode: status,
        ...result,
      })
    })
    .catch(error => {
      // console.log(JSON.stringify(error.response));
      console.log(error)
      message.destroy()
      const { response, message } = error
      if (String(message) === CANCEL_REQUEST_MESSAGE) {
        return {
          success: false,
        }
      }

      let msg
      let statusCode

      if (response && response instanceof Object) {
        const { data, statusText } = response
        statusCode = data.code
        msg =
          data.error &&
          data.error.replace('com.avos.avoscloud.AVException: ', '') //|| statusText
      } else {
        statusCode = 600
        msg = error.error || '服务器未响应，请稍后再试！'
      }

      switch (statusCode) {
        case 5001:
        case 5002:
          // console.log("push");
          router.push({
            pathname: '/login',
          })
          break
      }
      /* eslint-disable */
      return Promise.reject({
        success: false,
        statusCode,
        message: msg,
      })
    })
}
